import { CENTEREVENTS, EventsRes, KEYBOARD_KEY } from '@amcax/base';
import { nextmeshEventCenter } from '@app-nextmesh/common/events/EventCenter';
import { nmAppErrorLog, Picker } from '@app-nextmesh/common/utils';
import { CommandDialog2 } from '@app-nextmesh/components/Dialogs';
import {
  IMeshSeed,
  ModelEventType,
  ModelPickEvent,
  ModelPickTypesEvent,
  ModelTheme,
  NMMeshSeedCmdDialogParams,
} from '@app-nextmesh/types';
import { events, handleSelect } from '@app-nextmesh/utils';
import { clearPoints, renderPoints } from '@app-nextmesh/utils/renderModel';
import { useEffect, useRef, useState } from 'react';
import { MeshDialogFooter } from './MeshDialogFooter';
import { pickTypes, schema, uiSchema } from './seedJsonSchema';

type IParams = {
  editType: 'increaseAndDecrease'; // 进入点选增加减少节点流程
};
function BaseSeedDialog({
  title,
  onClose,
  request,
  params,
}: NMMeshSeedCmdDialogParams<IParams>) {
  const [formData, setFormData] = useState<IMeshSeed>(null);
  const [loading, setLoading] = useState(false);
  const keys = useRef<string[]>([]);

  const onPointerMove = (ev: EventsRes<PointerEvent>) => {
    // 只需要在pointer move时，设置可以选中的实体列表，当pointerdown/up之后就自动选择对应的实体
    Picker().pick(ev, { line: true });
  };
  const onPointerUp = (ev: EventsRes<PointerEvent>) => {
    const { button } = ev;
    if (!button.onLeft && !button.onRight) {
      return;
    }
    const selected = Picker().select2();
    const cKeys = keys.current;
    // 包含SHIFT键，但不包含CTRL，则取消已选中
    const hasCtrl = cKeys.includes(KEYBOARD_KEY.CTRL);
    const cancelSelected = cKeys.includes(KEYBOARD_KEY.SHIFT) && !hasCtrl;
    const ids = handleSelect(selected, ModelTheme.Source, cancelSelected);
    if (ids.length === 0) {
      return;
    }
    events.emit(ModelEventType.Pick, {
      indices: ids,
      selected: true,
    } as ModelPickEvent);
    if (params?.editType === 'increaseAndDecrease' && hasCtrl) {
      // 对当前选中的边
      if (button.onLeft) {
        // 增加 节点
      } else if (button.onRight) {
        // 减少 节点
      }
    }
  };
  const onKeyDown = (ev: EventsRes<KeyboardEvent>) => {
    if (ev.key && !keys.current.includes(ev.key)) {
      keys.current.push(ev.key);
    }
  };
  const onKeyUp = (ev: EventsRes<KeyboardEvent>) => {
    if (ev.key && keys.current.includes(ev.key)) {
      keys.current.splice(keys.current.indexOf(ev.key), 1);
    }
  };
  const exitCommand = () => {
    Picker().clickNull();
    Picker().init();
    nextmeshEventCenter()
      .off(CENTEREVENTS.POINTERMOVE, onPointerMove)
      .off(CENTEREVENTS.POINTERUP, onPointerUp)
      .off(CENTEREVENTS.KEYDOWN, onKeyDown)
      .off(CENTEREVENTS.KEYUP, onKeyUp)
      .setDefault();
  };
  useEffect(() => {
    // 设置当前支持的拾取类型
    events.emit(ModelEventType.PickTypes, {
      types: pickTypes,
    } as ModelPickTypesEvent);
    nextmeshEventCenter()
      .setState('cmd-mesh-seed')
      .on(CENTEREVENTS.POINTERMOVE, onPointerMove)
      .on(CENTEREVENTS.POINTERUP, onPointerUp)
      .on(CENTEREVENTS.KEYDOWN, onKeyDown)
      .on(CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      clearPoints();
      exitCommand();
    };
  }, []);

  const onSubmit = async (data) => {
    if (data) {
      setFormData(data);
      try {
        setLoading(true);
        const points = await request(data);
        renderPoints(points);
      } catch (error) {
        nmAppErrorLog('cmd-mesh-seed', 'onSubmit', error);
      } finally {
        setLoading(false);
      }
    }
  };
  return (
    <CommandDialog2
      title={title}
      formData={formData}
      onClose={onClose}
      schema={schema}
      extraUiSchema={uiSchema}
      onSubmit={onSubmit}
      submitLoading={loading}>
      <MeshDialogFooter onCancel={onClose} />
    </CommandDialog2>
  );
}

export { BaseSeedDialog };
